package com.shanhesoft.java.common.config;

import java.net.URI;
import java.util.Base64;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

import org.java_websocket.WebSocket.READYSTATE;
import org.java_websocket.drafts.Draft_6455;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import com.shanhesoft.java.common.rancher.Rancher;
import com.shanhesoft.java.common.rancher.base.TypeCollection;
import com.shanhesoft.java.common.rancher.service.HostService;
import com.shanhesoft.java.common.rancher.service.HoststatsService;
import com.shanhesoft.java.common.rancher.type.Host;
import com.shanhesoft.java.common.rancher.type.Hoststats;
import com.shanhesoft.java.common.ws.HoststatsWebSocketClient;
import com.shanhesoft.java.modules.exam.util.PropertiesUtils;
import com.shanhesoft.java.modules.exam.util.RancherUtils;

import retrofit2.Response;

@Component
@EnableScheduling   // 1.开启定时任务
@EnableAsync        // 2.开启多线程
public class RancherHostSchelduleTask {

	private Logger logger = LoggerFactory.getLogger(getClass());
	
	public static final Map<String, HoststatsWebSocketClient> HOST_WS_MAP = new ConcurrentHashMap<String, HoststatsWebSocketClient>();

	private static final String accessKey = PropertiesUtils.getProperty("rancher.accessKey");
	private static final String secretKey =PropertiesUtils.getProperty("rancher.secretKey");
	private static Rancher rancher = RancherUtils.getInstance();
	private static Rancher rancher_v2 = RancherUtils.getInstanceV2();
	
	@Scheduled(fixedDelay = 1000*60)  //间隔1分钟
	public void startHoststatsWS() {
		HostService hostService = rancher_v2.type(HostService.class);
		Map<String, String> tmpFilters = new HashMap<String, String>();
		tmpFilters.put("state_eq", "active");
		try {
			Response<TypeCollection<Host>> execute = hostService.list(tmpFilters).execute();
			logger.info("WS获取ranchera的ctive主机请求状态：{}", execute.isSuccess());
			if(execute.isSuccess()) {
				List<Host> data = execute.body().getData();
				logger.info("WS获取ranchera的ctive主机列表：{}", data);
				if(data != null && !data.isEmpty()) {
					logger.info("WS获取ranchera的ctive主机数量：{}", data.size());
					Set<String> keySet = HOST_WS_MAP.keySet();
					for (Host host : data) {
						String id = host.getId();
						String state = host.getState();
						logger.info("WS获取ranchera的ctive主机编号：{}, 主机状态：{}", id, state);
						if(!"active".equalsIgnoreCase(state)) {
							continue;
						}
						if(!keySet.contains(id)) {
							HoststatsService hoststatsService = rancher.type(HoststatsService.class);
							Response<Hoststats> executeHoststats = hoststatsService.get(id).execute();
							String token = "";
							String url = "";
							if(executeHoststats.isSuccess()) {
								Hoststats body = executeHoststats.body();
								token = body.getToken();
								url = body.getUrl();
							}
							if(StringUtils.isEmpty(token) || StringUtils.isEmpty(url)) {
								logger.error("token和url为空！");
								continue;
							}
							Map<String,String> headers = new HashMap<String, String>();
							String authorization = "Basic " + Base64.getEncoder().encodeToString((accessKey + ":" + secretKey).getBytes());
							headers.put("Authorization", authorization);
							HoststatsWebSocketClient webSocketClient = new HoststatsWebSocketClient(new URI(url+"?token="+token),new Draft_6455(), headers, 10000);
							webSocketClient.setHostId(id);
							webSocketClient.connectBlocking();
							HOST_WS_MAP.put(id, webSocketClient);
							logger.info("ranchera的ctive主机新建WS连接主机id：{},WS状态：{}", id, webSocketClient.getReadyState());
						}else {
							HoststatsWebSocketClient hoststatsWebSocketClient = HOST_WS_MAP.get(id);
							READYSTATE readyState = hoststatsWebSocketClient.getReadyState();
							if(!READYSTATE.OPEN.equals(readyState)) {
								hoststatsWebSocketClient.connectBlocking();
							}
							logger.info("ranchera的ctive主机重连WS连接主机id：{},WS状态：{}", id, readyState);
						}
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
